package com.example.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.test.Dao.TypeDao;
import com.example.test.Dao.UsersDao;
import com.example.test.bean.DTO.input.UsersCreateInputDTO;
import com.example.test.bean.DTO.input.UsersUpdateInputDTO;
import com.example.test.bean.GoodType;
import com.example.test.bean.Users;
import com.example.test.common.model.PageModel;
import com.example.test.common.model.R;
import com.example.test.mapper.UsersMapper;
import com.example.test.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 管理员信息表 服务实现类
 * </p>
 *
 * @author dz
 * @since 2022-04-10
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private UsersDao usersDao;
    private final Logger LOGGER = LoggerFactory.getLogger(UsersService.class);
//
//
    //根据keyword查询
    public R getTypeByKeyword(String keyword, PageModel pageModel){
        try {
            Long current = pageModel.getCurrent();
            Long size = pageModel.getSize();
            Long offset = (current - 1) * size;
            List<Users> usersList = usersDao.getUsersByKeyword(keyword,size,offset);
            if(usersList.size()>0){
                return R.success(usersList);
            }
            return R.error("未找到对应的账户");
        } catch (Exception e) {
            LOGGER.error("", e);
            return R.error("查询用户失败:" + e.getMessage());
        }
    }
//
    //根据id查询
    public R getUserById(Long userId){
        try {
            Users users = usersDao.getUserById(userId);
            if(users != null){
                return R.success(users);
            }
            return R.error("查询失败");
        } catch (Exception e) {
            LOGGER.error("", e);
            return R.error("查询分类失败:" + e.getMessage());
        }
    }

    //新增用户
    public R addUser(UsersCreateInputDTO usersCreateInputDTO){
        try {
            Date time = new Date();
            Users newUser = new Users();
            //查询是否有对应的user，如果没有，则新增
            String userName = usersCreateInputDTO.getUserName();
            if(userName.length()<1 || userName == null) {
                return R.error("用户名非法");
            }
            Users oldUser = usersDao.getUserByName(userName);
            if(oldUser == null){
                newUser.setDeleted(false);
                newUser.setCreateTime(time);
                newUser.setUserName(usersCreateInputDTO.getUserName());
                newUser.setUserNickname(usersCreateInputDTO.getUserNickname());
                newUser.setPassword(usersCreateInputDTO.getPassword());
                newUser.setUserType(usersCreateInputDTO.getUserType());
                Integer addUser = usersDao.insert(newUser);
                if(addUser == 0){
                    return R.error("新建User失败");
                }
                return R.success("插入成功" + addUser);
            }return R.error("用户名重复！");
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("新增用户失败:" + e.getMessage());
        }
    }

    //更新用户
    public R updateUser(UsersUpdateInputDTO usersUpdateInputDTO){
        try {
            Users newUser = new Users();
            //查询username是否合法
            String userName = usersUpdateInputDTO.getUserName();
            if(userName.length()<1 || userName == null) {
                return R.error("用户名非法");
            }
            //查询password是否合法
            String password = usersUpdateInputDTO.getPassword();
            if(password.length()<1 || password == null) {
                return R.error("密码非法");
            }
            //查询nickname是否合法
            String nickname = usersUpdateInputDTO.getUserNickname();
            if(nickname.length()<1 || nickname == null) {
                return R.error("用户名非法");
            }
            newUser.setDeleted(false);
            newUser.setUserId(usersUpdateInputDTO.getUserId());
            newUser.setUserName(usersUpdateInputDTO.getUserName());
            newUser.setUserNickname(usersUpdateInputDTO.getUserNickname());
            newUser.setPassword(usersUpdateInputDTO.getPassword());
            newUser.setUserType(usersUpdateInputDTO.getUserType());
            Integer updateUser = usersDao.updateById(newUser);
            if(updateUser == 0){
                return R.error("更新User失败");
            }
            return R.success("更新用户成功" + updateUser);
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("更新用户失败:" + e.getMessage());
        }
    }

    //删除用户
    public R deleteUser(Long userId){
        try {
            Date time = new Date();
            Users deleteUser = new Users();
            deleteUser.setUserId(userId);
            deleteUser.setDeleted(true);
            deleteUser.setDeletedTime(time);
            Users oldUser = usersDao.getUserById(userId);
            if(oldUser == null){
                R.error("未找到对应用户 删除失败");
            }
            //更新数据库
            int deletenum = usersDao.updateById(deleteUser);
            if(deletenum == 0){
                return R.error("删除用户失败：deletenum为0");
            }
            return R.success("删除用户成功:"+ userId);
        }catch(Exception e) {
            LOGGER.error("", e);
            return R.error("删除用户失败:" + e.getMessage());
        }
    }

    public String login(HttpServletRequest request, HttpServletResponse response,
                        String username, String password){
        //获取登录状态
        String result = (String) request.getAttribute("verification result");
        if("logged in".equals(result)) {//校验用户是否已经登录
            System.out.println("用户已登录");
            return "already logined";
        }
        if(!"123456789".equals(username)) {//校验用户名称
            System.out.println("用户不存在");
            return "user not found";
        }
        if(!"123456".equals(password)) {//校验用户密码
            System.out.println("账号或密码错误");
            return "账号或密码错误";
        }
        //生成一个token
        String token = UUID.randomUUID().toString();
        System.out.println("用户登录成功，获得token:" + token);
        HttpSession session = request.getSession();
        //服务端备份token
        session.setAttribute("token", token);
        //返回token
        return token;
    }
}
